#include "TcpServer.hpp"
#include "Socket.hpp"
#include "Accepter.hpp"
#include <memory>
#include <iostream>

using namespace NetWorkModule;

static const int gbacklog = 32;

void Usage(std::string process)
{
    std::cerr << "Usage: " << process << " port" << std::endl;
}

void Test(Connection *conn)
{
    std::cout << "get event, sockfd is : " << conn->SockFd() << std::endl;
}

// 这个代码是什么鬼？？？Reator : 反应堆模式，半同步半异步模式，Linux高并发服务器最常见的模式(没有之一)
// ./epoll_server 8888
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return 1;
    }

    int port = std::stoi(argv[1]);

    // 1. 创建listensock
    std::unique_ptr<Socket> listensock = std::make_unique<TcpSocket>(); // 3
    listensock->BuildListenSocketMethod(port, gbacklog);
    
    // 2. 创建tcpserver
    std::unique_ptr<TcpServer> svr = std::make_unique<TcpServer>();
    std::unique_ptr<Accepter> accepter = std::make_unique<Accepter>();
    auto listen_recver = std::bind(&Accepter::AccepterConnection, accepter.get(), std::placeholders::_1);

    // 4. 构建listen对应的connection，添加到tcpserver中
    Connection *conn = ConnectionFactory::BuildListenConnection(listensock->GetSockFd(),
                                                                listen_recver,
                                                                EPOLLIN | EPOLLET,
                                                                svr.get());
    svr->AddConnection(conn);

    // 5. 开始事件派发
    svr->Dispatcher(); // 开始事件派发啦
    return 0;
}